package com.msl.debezium.jdbc;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.vm")
    public DataSource defaultDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.win")
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 暂时只有2个数据源
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.other")
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DataSource dynamicDataSource(DataSource defaultDataSource, DataSource dataSource1, DataSource dataSource2) {
        // 注意：该方法的参数名称要和前面前面三个datasource对象在Spring容器中的bean名称一样
        // 或者使用 @Qualifier 指定具体的bean
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.VM.name(), defaultDataSource);
        targetDataSources.put(DataSourceType.WIN.name(), dataSource1);
        targetDataSources.put(DataSourceType.OTHER.name(), dataSource2);
        return new DynamicDataSource(defaultDataSource, targetDataSources);
    }
}
